package com.elm.service.impl;

import com.elm.mapper.BusinessMapper;
import com.elm.po.Business;
import com.elm.po.User;
import com.elm.service.BusinessService;
import com.elm.service.UserService;
import com.elm.util.JwtUtil;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List; 

@Service
public class BusinessServiceImpl implements BusinessService {

    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private UserService userService; // 用于验证用户存在性
    @Autowired
    private HttpServletRequest request; // 获取请求中的Token

    // 公共方法：从Token获取当前用户ID
    private String getCurrentUserId() {
        String token = (String) request.getAttribute("token");
        return JwtUtil.getUserIdFromToken(token);
    }

    // 公共方法：从Token获取当前用户类型
    private String getCurrentUserType() {
        String token = (String) request.getAttribute("token");
        return JwtUtil.getUserTypeFromToken(token);
    }

    @Override
    public List<Business> getBusinessByOrderTypeId(Integer orderTypeId) {
        // 无需权限验证，公开接口
        return businessMapper.getBusinessByOrderTypeId(orderTypeId);
    }

    @Override
    public Business getBusinessById(Integer businessId) {
        // 无需权限验证，公开接口
        return businessMapper.getBusinessById(businessId);
    }

    @Override
    public List<Business> getBusinessBySales() {
        // 按销量排序，仅查询营业中商家
        return businessMapper.getBusinessBySales("opening");
    }

    @Override
    public List<Business> getBusinessByStar() {
        // 按评分排序
        return businessMapper.getBusinessByStar();
    }

    // Admin专属：获取所有待审核商家
    @Override
    public List<Business> getAllReviewingBusiness() {
        // 验证当前用户是否为Admin
        if (!"admin".equals(getCurrentUserType())) {
            throw new RuntimeException("权限不足：仅管理员可查看待审核商家");
        }
        return businessMapper.getAllReviewingBusiness();
    }

    // Admin专属：审核商家
    @Override
    public int updateReviewingBusinessInfo(Integer businessId, boolean result) {
        if (!"admin".equals(getCurrentUserType())) {
            throw new RuntimeException("权限不足：仅管理员可审核商家");
        }
        // result为true则通过，更新状态为opening；否则拒绝
        String status = result ? "opening" : "rejected";
        return businessMapper.updateReviewingBusinessInfo(businessId, status);
    }

    // 商家Boss专属：创建商家（发起开店请求）
    @Override
    public int createBusiness(Business business) {
        String userType = getCurrentUserType();
        String userId = getCurrentUserId();
        // 验证当前用户是否为boss
        if (!"boss".equals(userType)) {
            throw new RuntimeException("权限不足：仅商家老板可发起开店请求");
        }
        // 关联商家与boss（User表中businessId字段）
        business.setBusiness_status("reviewing"); // 初始状态为待审核
        int rows = businessMapper.createBusiness(business);
        if (rows > 0) {
            // 更新用户表中boss对应的businessId
            User user = new User();
            user.setUserId(userId);
            user.setBusinessId(business.getBusinessId());
            userService.updateUser(user);
        }
        return rows;
    }

    // 商家Boss专属：更新商家信息
    @Override
    public int updateBusiness(Business business) {
        String userId = getCurrentUserId();
        String userType = getCurrentUserType();
        if (!"boss".equals(userType)) {
            throw new RuntimeException("权限不足：仅商家老板可修改商家信息");
        }
        // 验证当前boss是否属于该商家（通过User表的businessId关联）
        User user = userService.getUserById(userId); // 需实现根据userId查询用户的方法
        if (!business.getBusinessId().equals(user.getBusinessId())) {
            throw new RuntimeException("无权限：不能修改其他商家信息");
        }
        return businessMapper.updateBusiness(business);
    }

    // 商家Staff专属：更新商家营业状态（开门/关门） 
    @Override
    public int updateBusinessStatus(Business business) {
        String userType = getCurrentUserType();
        if (!"staff".equals(userType)) {
            throw new RuntimeException("权限不足：仅商家员工可修改营业状态");
        }
        // 验证staff所属商家（通过User表的businessId）
        String staffId = getCurrentUserId();
        User staff = userService.getUserById(staffId);
        if (!business.getBusinessId().equals(staff.getBusinessId())) {
            throw new RuntimeException("无权限：不能修改其他商家状态");
        }
        return businessMapper.updateBusinessStatus(business.getBusinessId(), business.getBusiness_status());
    }
}